package com.dachuang.canjiren.service.impl;

import com.dachuang.canjiren.entity.*;
import com.dachuang.canjiren.mapper.CommentMapper;
import com.dachuang.canjiren.mapper.LawMapper;
import com.dachuang.canjiren.mapper.UserMapper;
import com.dachuang.canjiren.service.LawService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dachuang.common.exception.BizCodeEnume;
import com.dachuang.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-27
 */
@Service
public class LawServiceImpl extends ServiceImpl<LawMapper, Law> implements LawService {
    @Autowired
    private LawMapper lawMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public R insertLaw(Integer userId, String title,String content, String name, Integer status) {
        if (Objects.isNull(userId)){
            return R.error(BizCodeEnume.ERROR20006);
        }
        if (StringUtils.isEmpty(title)){
            return R.error(BizCodeEnume.ERROR80004);
        }
        if (StringUtils.isEmpty(name)){
            return R.error(BizCodeEnume.ERROR50001);
        }
        if (StringUtils.isEmpty(content)){
            return R.error(BizCodeEnume.ERROR30002);
        }
        //验证userId
        User user = userMapper.selectById(userId);
        if (Objects.isNull(user)){
            return R.error(BizCodeEnume.ERROR20004);
        }

        //插入到表
        Law law = new Law();
        law.setUserId(userId);
        law.setTitle(title);
        law.setContent(content);
        law.setName(name);
        law.setStatus(status);
        if (lawMapper.insertLaw(law) > 0){
            return R.ok();
        }
        return R.error();
    }

    @Override
    public R selectLaw(Integer id) {
        if (Objects.isNull(id)){
            return R.error(BizCodeEnume.ERROR20005);
        }
        Law law = lawMapper.selectLaw(id);
        if (Objects.isNull(law)){
            return R.error(BizCodeEnume.ERROR30003);
        }
        R r = R.ok();
        r.put("data",law);
        return r;
    }

    @Override
    public R selectLawList() {
        List<Law> list = lawMapper.selectLawList();
        Map<String,Object> map = new HashMap<>();
        if (list.size() > 0){
            map.put("data",list);
            return R.ok(map);
        }
        return R.error();
    }
}
